package com.tangjinghao.monitor

import android.app.AlertDialog
import android.content.Context
import android.content.pm.ActivityInfo
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.DisplayMetrics
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.widget.MediaController
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.qmuiteam.qmui.util.QMUIStatusBarHelper
import com.tangjinghao.monitor.databinding.ActivityControllerViewBinding
import com.tangjinghao.monitor.databinding.DialogLearnBinding
import com.tangjinghao.monitor.util.Constants
import com.tangjinghao.monitor.util.TimeCalendar
import com.zhangke.websocket.WebSocketHandler
import com.zhangke.websocket.WebSocketManager
import com.zhangke.websocket.WebSocketSetting
import com.zhangke.websocket.dispatcher.IResponseDispatcher
import com.zhangke.websocket.dispatcher.ResponseDelivery
import com.zhangke.websocket.response.ErrorResponse
import org.java_websocket.framing.Framedata
import java.nio.ByteBuffer


class MainActivity : AppCompatActivity() {
    companion object {
        const val WB_URL = "ws://47.100.93.186:8089/option/MOBILE"
    }
    //WB
    private lateinit var webSocketManager: WebSocketManager
    private val webSocketSetting = WebSocketSetting()
    //config
    private lateinit var mBinding: ActivityControllerViewBinding
    private lateinit var mMediaController: MediaController
    private lateinit var mUri: String
    private var mFlag = false//判断模式，否为编程模式，是为监控模式
    private lateinit var mDialogLearnBinding: DialogLearnBinding
    private lateinit var builder: AlertDialog.Builder
    private lateinit var dialog: AlertDialog
    private var mStudyEndTime = "未记录"
    private var mStudyStartTime = "未记录"
    private var mLeaveStartTime = "未记录"
    private var mLeaveEndTime = "未记录"
    private var mStatus="离开"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mLeaveStartTime = TimeCalendar.getTime()
        initWB(this)
        initConfig()
        setHideVirtualKey(this.window)
        setContentView(mBinding.root)
        initListener()
    }


    /**
     * 设置监听
     */
    private fun initListener() {
        initMovingListener()
        initHandListener()
        mBinding.monitorBtn.setOnClickListener {
            if (!mFlag) {
                showToast("编程模式下无法开启视频")
            } else {
                showToast("开启监控")
                setData()
            }
        }
        mBinding.recordTimeBtn.setOnClickListener {
            dialogShowing()
        }
        mBinding.modeChangeBtn.setOnClickListener {
            if (!mFlag) {
                //如果不能点击，则为编程模式,此时切换为监控模式
                mFlag = true
                mBinding.modeChangeBtn.text = "监控模式"
                showToast("监控模式")
                sendDataToClient(Constants.MONITOR_MOD)
            } else {
                mFlag = false
                mBinding.modeChangeBtn.text = "编程模式"
                showToast("编程模式")
                sendDataToClient(Constants.PROGRAM_MOD)
            }
        }
    }

    private fun initHandListener() {
        mBinding.handUp.setClickListener {
            Log.d("======", "handUp")
            sendDataToClient(Constants.HAND_UP)
        }
        mBinding.handRight.setClickListener {
            Log.d("======", "handRight")
            sendDataToClient(Constants.HAND_RIGHT)
        }
        mBinding.handLeft.setClickListener {
            Log.d("======", "handLeft")
            sendDataToClient(Constants.HAND_LEFT)
        }
        mBinding.handDown.setClickListener {
            Log.d("======", "handDown")
            sendDataToClient(Constants.HAND_DOWN)
        }
    }

    private fun initMovingListener() {
        mBinding.moveUp.setClickListener {
            Log.d("======", "moveUp")
            sendDataToClient(Constants.CAR_UP)
        }
        mBinding.moveDown.setClickListener {
            Log.d("======", "moveDown")
            sendDataToClient(Constants.CAR_DOWN)
        }
        mBinding.moveLeft.setClickListener {
            Log.d("======", "moveLeft")
            sendDataToClient(Constants.CAR_LEFT)
        }
        mBinding.moveRight.setClickListener {
            Log.d("======", "moveRight")
            sendDataToClient(Constants.CAR_RIGHT)
        }
    }

    /**
     * 初始化数据
     */
    private fun setData() {
        mBinding.videoView.visibility = View.VISIBLE
        mBinding.videoViewBtn.visibility = View.GONE
        mBinding.videoView.setVideoURI(Uri.parse(mUri))
        mMediaController.setMediaPlayer(mBinding.videoView)
        mBinding.videoView.start()
        mBinding.videoView.setMediaController(mMediaController)
//        Handler(Looper.getMainLooper()).postDelayed(Runnable {
//
//        }, 1000)
    }

    /**
     * 初始化配置
     */
    private fun initConfig() {
        QMUIStatusBarHelper.translucent(this)
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;//设置屏幕为横屏, 设置后会锁定方向
        QMUIStatusBarHelper.setStatusBarLightMode(this)
        mBinding = ActivityControllerViewBinding.inflate(layoutInflater)
        mMediaController = MediaController(this)
        mUri = "android.resource://" + packageName + "/" + R.raw.hoshi
    }

    override fun onResume() {
        super.onResume()
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;//设置屏幕为横屏, 设置后会锁定方向
    }

    private fun showToast(msg: String) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    private fun setHideVirtualKey(window: Window) {
        //保持布局状态
        var uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or  //布局位于状态栏下方
                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or  //全屏
                View.SYSTEM_UI_FLAG_FULLSCREEN or  //隐藏导航栏
                View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
        uiOptions = if (Build.VERSION.SDK_INT >= 19) {
            uiOptions or 0x00001000
        } else {
            uiOptions or View.SYSTEM_UI_FLAG_LOW_PROFILE
        }
        window.decorView.systemUiVisibility = uiOptions
    }

    /**
     * 修改弹窗大小
     * @param myWidth 长度缩小倍数
     */
    private fun changeDialogSize(
        dialog: AlertDialog,
        myWidth: Float,
    ) {
        val windowManager: WindowManager = windowManager
        val dm = DisplayMetrics()
        val window = dialog.window
        //设置动画
        window?.setWindowAnimations(R.style.dialog_animation)
        val p = window!!.attributes
        windowManager.defaultDisplay.getMetrics(dm)
        p.width = (dm.widthPixels * myWidth).toInt()
        window.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        window.attributes = p
        window.setGravity(Gravity.CENTER_VERTICAL)
    }

    /**
     * 共有的dialog显示方法
     */
    private fun dialogShowing() {
        builder = AlertDialog.Builder(this)
        mDialogLearnBinding = DialogLearnBinding.inflate(layoutInflater)
        builder.setView(mDialogLearnBinding.root)
        dialog = builder.create()
        dialog.setCancelable(false)
        if(!dialog.isShowing){
            dialog.show()
            initDialog()
            mDialogLearnBinding.sureBtn.setOnClickListener {
                dialog.dismiss()
            }
            changeDialogSize(dialog, 0.55f)

        }
    }

    private fun initDialog() {
        mDialogLearnBinding.leaveRecordStartTv.text = mLeaveStartTime
        mDialogLearnBinding.leaveRecordEndTv.text = mLeaveEndTime
        mDialogLearnBinding.studyRecordStartTv.text = mStudyStartTime
        mDialogLearnBinding.studyRecordEndTv.text = mStudyEndTime
    }

    /**
     * 初始化WebSocket
     */
    private fun initWB(context: Context) {
        webSocketSetting.connectUrl = WB_URL
        webSocketSetting.connectTimeout = 10 * 1000
        webSocketSetting.connectionLostTimeout = 60
        webSocketSetting.reconnectFrequency = 40
        webSocketSetting.setReconnectWithNetworkChanged(true)
        webSocketSetting.setResponseProcessDispatcher(
            object : IResponseDispatcher {
                override fun onConnected(delivery: ResponseDelivery?) {

                }

                override fun onConnectFailed(cause: Throwable?, delivery: ResponseDelivery?) {

                }

                override fun onDisconnect(delivery: ResponseDelivery?) {

                }

                override fun onMessage(message: String, delivery: ResponseDelivery) {
                    if (message == Constants.X) {
                        mLeaveEndTime=TimeCalendar.getTime()
                        mStatus="学习"
                        if(mStudyStartTime=="未记录"){
                            mStudyStartTime=TimeCalendar.getTime()
                        }
                    } else if (message == Constants.L) {
                        mStatus="离开"
                        mStudyEndTime=TimeCalendar.getTime()
                    }
                }

                override fun onMessage(byteBuffer: ByteBuffer?, delivery: ResponseDelivery?) {

                }

                override fun onPing(framedata: Framedata?, delivery: ResponseDelivery?) {

                }

                override fun onPong(framedata: Framedata?, delivery: ResponseDelivery?) {

                }

                override fun onSendDataError(error: ErrorResponse?, delivery: ResponseDelivery?) {

                }
            })
        webSocketSetting.setProcessDataOnBackground(true)
        WebSocketHandler.registerNetworkChangedReceiver(context)
        webSocketManager = WebSocketHandler.init(webSocketSetting)
        webSocketManager.start()
    }

    /**
     * 发送数据给后台
     */
    private fun sendDataToClient(msg: String) {
        webSocketManager.send(msg)
    }


}